import { ElMessage } from 'element-plus';

export const formatBlock = (code) => {
    if (code.startsWith('688')) {
        return '科创板';
    } else if (code.startsWith('300') || code.startsWith('301')) {
        return '创业板';
    } else if (code.startsWith('8')) {
        return '北交所';
    } else {
        return '主板';
    }
};

// 格式化价格
export const formatPrice = (price, precision = 2) => {
    if (!price && price !== 0) return '--';
    return Number(price).toLocaleString('zh-CN', {
        minimumFractionDigits: precision,
        maximumFractionDigits: precision
    });
};

// 格式化主力资金
export const formatMainMoney = (money) => {
    if (!money || money === '-') return 0;
    return (money / 100000000).toFixed(2) + '亿';
};

// 获取量化颜色
export const getScoreColor = (score) => {
    if (score >= 75) return '#f56c6c';
    if (score >= 65) return '#67C23A';
    if (score >= 50) return '#E6A23C';
    return '#909399';
};

// 量化结果
export const getRecommendation = (score) => {
    if (score >= 75) return '强烈推荐'; // 各项指标都很优秀
    if (score >= 65) return '建议买入'; // 大部分指标表现良好
    if (score >= 50) return '可以关注'; // 有一定投资价值
    if (score >= 20) return '需要观察'; // 观察变化趋势
    if (score >= 0) return '保持观望'; // 等待更好时机
    if (score >= -20) return '注意风险'; // 存在一定风险
    return '建议规避'; // 风险较大
};

// 量化类型
export const getRecommendationType = (score) => {
    if (score >= 75) return 'danger'; // 各项指标都很优秀
    if (score >= 65) return 'success'; // 大部分指标表现良好
    if (score >= 50) return 'warning'; // 有一定投资价值
    return 'info'; // 风险较大
};

// 格式化浮动盈亏
export const formatProfit = (stock) => {
    const profit = (stock.price - stock.costPrice) * stock.quantity;
    return formatPrice(profit, 2);
};

// 格式化收益率
export const formatProfitPercent = (stock) => {
    const profitPercent =
        ((stock.price - stock.costPrice) / stock.costPrice) * 100;
    return (profitPercent >= 0 ? '+' : '') + profitPercent.toFixed(2) + '%';
};

// 高抛低吸Tip
export const calculateDealTool = ({ lowPrice, highPrice }) => {
    if (!lowPrice || lowPrice.length < 3) return '-';
    if (!highPrice || highPrice.length < 3) return '-';

    const [low, fifteenLow, thirtyLow] = lowPrice;
    const [thirtyHigh, fifteenHigh, high] = highPrice;
    return `最低价：${low}，次低价：${fifteenLow}，第三低：${thirtyLow}；第三高：${thirtyHigh}，次高价：${fifteenHigh}，最高价：${high}`;
};

// 计算高抛低吸CSS
export const calculateDealUI = ({ name, price, lowPrice, highPrice }) => {
    // if (name.indexOf('ST') !== -1) return '';
    if (!lowPrice || lowPrice.length < 3) return '';
    if (!highPrice || highPrice.length < 3) return '';

    const [low, fifteenLow, thirtyLow] = lowPrice;
    const [thirtyHigh, fifteenHigh, high] = highPrice;

    if (price <= thirtyLow && price > fifteenLow) {
        return 'buy';
    }
    if (price <= fifteenLow && price > low) {
        return 'buy-600';
    }
    if (price <= low) {
        return 'buy-800';
    }
    if (price > thirtyLow && price < thirtyHigh) {
        return 'shake';
    }
    if (price >= high) {
        return 'sell-800';
    }
    if (price < high && price >= fifteenHigh) {
        return 'sell-600';
    }
    if (price < fifteenHigh && price >= thirtyHigh) {
        return 'sell';
    }
    return '';
};

// 计算高抛低吸
export const calculateDeal = ({ name, price, lowPrice, highPrice }) => {
    // if (name.indexOf('ST') !== -1) return '-';
    if (!lowPrice || lowPrice.length < 3) return '-';
    if (!highPrice || highPrice.length < 3) return '-';

    const [low, fifteenLow, thirtyLow] = lowPrice;
    const [thirtyHigh, fifteenHigh, high] = highPrice;

    if (price < thirtyLow) {
        return '吸';
    }
    if (price > thirtyHigh) {
        return '抛';
    }
    return '震荡';
};

// 复制股票代码
export const handleCopy = async (code) => {
    if ('clipboard' in navigator) {
        navigator.clipboard
            .writeText(code)
            .then(() => {
                ElMessage({
                    message: `股票代码 ${code} 已复制`,
                    type: 'success',
                    duration: 1500
                });
            })
            .catch(() => {
                copyTextToClipboard(code);
            });
    } else {
        copyTextToClipboard(code);
    }
};

const copyTextToClipboard = (text) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        const successful = document.execCommand('copy');
        if (successful) {
            ElMessage({
                message: `股票代码 ${text} 已复制`,
                type: 'success',
                duration: 1500
            });
        }
    } catch (err) {
        console.error('复制文本时出错:', err);
    }
    document.body.removeChild(textArea);
};

// 最高价排序
export const formatHighPriceSort = (historyPrice) => {
    if (!historyPrice || historyPrice.length < 30) return [];
    let first = 100,
        second = 50,
        third = 0;
    if (historyPrice.length < 500) {
        first = Math.floor(historyPrice.length / 5);
        second = Math.floor(historyPrice.length / 10);
    }
    let sortItem = historyPrice.sort((a, b) => b - a);
    return [sortItem[first], sortItem[second], sortItem[third]];
};

// 最低价排序
export const formatLowPriceSort = (historyPrice) => {
    if (!historyPrice || historyPrice.length < 30) return [];

    let first = 0,
        second = 50,
        third = 100;
    if (historyPrice.length < 500) {
        second = Math.floor(historyPrice.length / 10);
        third = Math.floor(historyPrice.length / 5);
    }
    let sortItem = historyPrice.sort((a, b) => a - b);
    return [sortItem[first], sortItem[second], sortItem[third]];
};

export const findMostFrequent = (arrays) => {
    let obj = {}, max = 0, maxEle;
    for (let i = 0; i < arrays.length; i++) {
        let val = arrays[i]
        obj[val] === undefined ? obj[val] = 1 : obj[val]++;
        if (obj[val] > max) {
            max = obj[val];
            maxEle = val;
        }
    }
    return maxEle;
}
